<?php
// +----------------------------------------------------------------------
// | Scallion 
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.scallion.top All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Liuxg < 420695648@qq.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use think\Validate;
class WxAdminController extends AdminBaseController
{
	public function user_info(){
		$id = cmf_get_current_admin_id();
		$user = db('user')->where(['id'=>$id])->field('id,sex,birthday,score,coin,balance,user_login,user_nickname,user_email,user_url,avatar,signature,last_login_ip,mobile,more')->find();
		$this->assign($user);
		return $this->fetch();
	}
	
	public function my_class(){
		$id = cmf_get_current_admin_id();
		$teacher = db('teacher')->where(['union_id'=>$id])->find();
		$classes = db('class')
		->where(['teacher'=>$teacher['id']])
		->alias('a')
		->join('classroom w','a.classroom_id = w.id')
		->field('a.id as id,a.name as name,a.class_number as class_number,w.name as classroom')
		->select()->toArray();
		$this->assign('class',$classes);
		return $this->fetch();
	}
	
	public function wx_get_class_timetable($param){
		$data = db('class_timetable')
			->where(['class_id'=>$param['id']])
			->alias('a')
			->join('class b','a.class_id = b.id')
			->join('classroom c','a.classroom_id = c.id')
			->field('a.id as id,b.name as class_name,c.name as classroom_name,a.class_number as class_number,a.times as times,start_time,end_time')
			->order('start_time asc')
			->select()->toarray();
			// 数据处理开始
			$assign_data = '';
			$date = '';
			$i = 0;
			foreach($data as $vo){
				if($date == date('Y-n-j',$vo['start_time'])){
					$i++;
					$assign_data[$date][$i]['title'] = '班级：'.$vo['class_name'].'</br>教室：'.$vo['classroom_name'].'</br>第'.$vo['times'].'/'.$vo['class_number'].'次课';
					$assign_data[$date][$i]['startTime'] = date('Y年n月j日 H:i',$vo['start_time']);
					$assign_data[$date][$i]['endTime'] = date('Y年n月j日 H:i',$vo['end_time']);
				}
				else{
					$date = date('Y-n-j',$vo['start_time']);
					$i = 0;
					$assign_data[$date][$i]['title'] = '班级：'.$vo['class_name'].'</br>教室：'.$vo['classroom_name'].'</br>第'.$vo['times'].'/'.$vo['class_number'].'次课';
					$assign_data[$date][$i]['startTime'] = date('Y年n月j日 H:i',$vo['start_time']);
					$assign_data[$date][$i]['endTime'] = date('Y年n月j日 H:i',$vo['end_time']);
				}
				$assign_data[$date][$i]['id'] = $vo['id'];
			}
			return $assign_data;
	}
	
	public function wx_class_timetable(){
		if($this->request->param()){
			$param = $this->request->param();
			$class = db('class')->where(['id'=>$param['id']])->find();
			$assign_data = $this->wx_get_class_timetable($param);
			$safe_url['user_name'] = $class['name'];
			$safe_url['timetable_data'] = json_encode($assign_data);
			$surl = new SurlController;
			$encode = $surl->encode('wxview/timetable','safe_url',$safe_url);
			$this->redirect($encode,302);
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function class_detail(){
		if($this->request->param()){
			$param = $this->request->param();
			// 课表数据
			$class_timetable = $this->wx_get_class_timetable($param);
			// 学生数据
			$students = db('class_student_sign_in')
			->where(['class_id'=>$param['id']])
			->alias('a')
			->join('student w','a.student_id = w.id')
			->field('w.phone as phone,w.phone2 as phone2,w.name as name')
			->order('convert(w.name using gbk) asc')
			->select()->toArray();
			// 考勤数据
			$attendance_data = db('class_timetable')
			->alias('a')
			->where(['class_id'=>$param['id']])
			->join('student_attendance att','att.timetable_id = a.id OR att.target = a.id')
			->join('student s','att.student_id = s.id')
			->field('a.id as id,att.student_id as student_id,s.name as student_name,s.phone as phone,s.phone2 as phone2,att.code as code,att.target as target')
			->select()->toArray();
			// 数据处理
			// 数据处理开始
			foreach($class_timetable as &$vo){
				foreach($vo as &$voo){
					$k = 0;
					foreach($attendance_data as &$att_data){
						if($att_data['target']==$att_data['id']&&$att_data['code'] ==2){
							$att_data['code'] = 5;
						}
						if($voo['id'] == $att_data['id']){
							$voo['student_data'][$k] = $att_data;
							$k++;
						}
					}
				}
			}
			// 输出模板
			$this->assign('students',$students);
			$this->assign('timetable_data',json_encode($class_timetable));
			$this->assign('param',$param);
			return $this->fetch();
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function my_setting(){
		return $this->fetch();
	}
	
	public function cancel_bind_wx(){
		$id = cmf_get_current_admin_id();
		$res = db("third_party_user")->where(["user_id"=>$id])->delete();
		if($res){
			session('ADMIN_ID', null);
			$this->success('解绑成功！',url('portal/index/index'));
		}
		else{
			$this->error('解绑失败！');
		}
	}
	
	public function change_password(){
		$id = cmf_get_current_admin_id();
		if($id){
			return $this->fetch();
		}
		else{
			return false;
		}
	}
	
	public function change_password_do(){
		if($this->request->param()){
			$id = cmf_get_current_admin_id();
			$param = $this->request->param();
			if($param['password']!=$param['re_password']){
				$this->error('两次输入密码不一致！');
			}
			if(strlen($param['password'])<6){
				$this->error('密码不能少于6位!');
			}
			$old = db('user')->where(['id'=>$id])->find();
			if($old){
				$is_match = cmf_compare_password($param['old_password'],$old['user_pass']);
				if($is_match){
					$data['user_pass'] = cmf_password($param['password']);
					if(db('user')->where(['id'=>$id])->update($data)){
						$this->success('修改密码成功！',url('portal/WxAdmin/user_info'));
					}
					else{
						$this->error('修改密码失败！');
					}
				}
				else{
					$this->error('旧密码不正确！');
				}
			}
			else{
				$this->error('非法访问！');
			}
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function tools(){
		return $this->fetch();
	}
	
	public function search_student(){
		return $this->fetch();
	}
	
	public function search_student_post(){
		if($this->request->param()){
			$param = $this->request->param();
			$res = db('student')
			->where('name','like','%'.$param['name'].'%')
			->where('phone|phone2','like','%'.$param['phone'].'%')
			// ->limit(10)
			->select();
			$this->assign('data',$res);
			return $this->fetch();
			// $this->error(json_encode($res));
		}
		else{
			$this->error('非法访问！');
		}
	}
	
	public function search_teacher(){
		return $this->fetch();
	}
	
	public function search_teacher_post(){
		if($this->request->param()){
			$param = $this->request->param();
			$res = db('teacher')
			->alias('a')
			->where('a.name','like','%'.$param['name'].'%')
			->where('a.phone','like','%'.$param['phone'].'%')
			->join('user w','w.id = a.union_id')
			->order('a.id asc')
			->field('a.id,a.name,a.phone,a.sex,w.user_email')
			->select();
			// ->paginate(15);
			// $this->assign('page', $res->render());
			$this->assign('data',$res);
			return $this->fetch();
			// $this->error(json_encode($res));
		}
		else{
			$this->redirect(url('portal/wx_admin/search_teacher'));
		}
	}
	
	public function search_class(){
		return $this->fetch();
	}
	
	public function search_class_post(){
		if($this->request->param()){
			$param = $this->request->param();
			$res = db('class')
			->alias('a')
			->where('a.name','like','%'.$param['name'].'%')
			->join('teacher t','t.id = a.teacher')
			->join('classroom c','c.id = a.classroom_id')
			->order('a.id asc')
			->field('a.id,a.name,t.name as teacher_name,c.name as classroom_name')
			->select();
			// ->paginate(2);
			// $this->assign('page', $res->render());
			$this->assign('data',$res);
			return $this->fetch();
			// $this->error(json_encode($res));
		}
		else{
			$this->redirect(url('portal/wx_admin/search_class'));
		}
	}
	
	public function class_attendance(){
		if(cookie('my_class_id')){
			cookie('select_class_redirect_url','class_attendance');
			$param = cookie('my_class_id');
			$class = db('class')->where(['id'=>$param])->find();
			$url = url('admin/class/class_attendance',['class_id'=>$param]);
			$this->assign('class',$class);
			$this->assign('url',$url);
			return $this->fetch();
		}
		else{
			cookie('select_class_redirect_url','class_attendance');
			$this->redirect(url('portal/wx_admin/select_class'));
		}
	}
	
	public function select_class(){
		$id = cmf_get_current_admin_id();
		$teacher = db('teacher')->where(['union_id'=>$id])->find();
		$classes = db('class')
		->where(['teacher'=>$teacher['id']])
		->alias('a')
		->join('classroom w','a.classroom_id = w.id')
		->field('a.id as id,a.name as name,a.class_number as class_number,w.name as classroom')
		->select()->toArray();
		$this->assign('class',$classes);
		return $this->fetch();
	}
	
	public function setcookie_class(){
		if($this->request->param()){
			$param = $this->request->param();
			$res = db('class')->where(['id'=>$param['id']])->find();
			if($res){
				cookie('my_class_id',$param['id']);
				$this->redirect(url('portal/wx_admin/'.$_COOKIE['select_class_redirect_url']));
			}
			else{
				$this->error('非法班级！',url('portal/wx_admin/select_class'));
			}
		}
		else{
			$this->redirect(url('portal/wx_admin/select_class'));
		}
	}
	
	public function class_blog(){
		if(cookie('my_class_id')){
			cookie('select_class_redirect_url','class_blog');
			$param = cookie('my_class_id');
			$this->redirect(url('portal/article/blog',['class_id'=>$param]));
		}
		else{
			cookie('select_class_redirect_url','class_blog');
			$this->redirect(url('portal/wx_admin/select_class'));
		}
	}
	
	public function class_attendance_turn(){
		$id = cmf_get_current_admin_id();
		$data = db('student_attendance')
		->alias('a')
		->where(['a.code'=>2,'a.edit_id'=>$id])
		->join('student s','s.id = a.student_id')
		->join('class_timetable t','t.id = a.timetable_id')
		->join('class c','c.id = t.class_id')
		->field('a.id as id,s.name as student_name,c.name as class_name,t.times as times,t.class_number as class_number,s.phone as phone')
		->order('a.last_edit_time desc')
		->select();
		if(count($data)>0){
			// dump($data);
			$this->assign('data',$data);
		};
		return $this->fetch();
	}
	
	public function class_attendance_turn_add(){
		// 选择班级
		$id = cmf_get_current_admin_id();
		$teacher = db('teacher')->where(['union_id'=>$id])->find();
		$classes = db('class')
		->where(['teacher'=>$teacher['id']])
		->alias('a')
		->join('classroom w','a.classroom_id = w.id')
		->field('a.id as id,a.name as name,a.class_number as class_number,w.name as classroom')
		->select()->toArray();
	
		$this->assign('class',$classes);
		return $this->fetch();
	}
	
	public function class_id_get_student(){
		if($this->request->param()){
			$param = $this->request->param();
			$data = db('class_student_sign_in')
				->alias('a')
				->where(['a.class_id'=>$param['class_id']])
				->join('student s','s.id = a.student_id')
				->field('s.id as id,s.name as student_name,s.phone,s.phone2')
				->order('convert(s.name using gbk) asc')
				->select()->toArray();
			return json($data);
		}
	}
	
	public function class_id_get_similar_class(){
		if($this->request->param()){
			// 查询原班所有分类
			$param = $this->request->param();
			$data = db('school_category_post')
			->alias('a')
			->where(['a.post_id'=>$param['class_id']])
			->join('school_category b','b.id = a.category_id')
			->order('LENGTH(b.path) desc,b.parent_id desc,b.id desc')
			->field('b.id as id,b.parent_id,b.name,b.path')
			->select()->toArray();
			// 遍历分类，输出分类班级
			$not_in = array($param['class_id']);
			foreach($data as $key=>$vo){
				$res[$key] = db('school_category_post')
				->alias('a')
				->where('a.post_id','not in',$not_in)
				->where(['a.category_id'=>$vo['id']])
				->join('class b','b.id = a.post_id')
				->join('classroom c','c.id = b.classroom_id')
				->join('teacher t','t.id = b.teacher')
				->field('b.id as class_id,b.name as class_name,c.name as classroom_name,t.name as teacher_name')
				->select()->toArray();
				
				foreach($res[$key] as $res_vo){
					array_push($not_in,$res_vo['class_id']);
				}
			}
			//其他剩余班级
			$rest_class = db('class')
			->alias('a')
			->where('a.id','not in',$not_in)
			->join('classroom c','c.id = a.classroom_id')
			->join('teacher t','t.id = a.teacher')
			->field('a.id as class_id,a.name as class_name,c.name as classroom_name,t.name as teacher_name')
			->select()->toArray();
			array_push($res,$rest_class);
			return json($res);
		}
	}
	
	public function class_attendance_turn_add_post(){
		if($this->request->param()){
			// 验证数据
			$param = $this->request->param();
			$rule = [
				'input_old_class_id'  => 'require|number',
				'input_student_id'  => 'require|number',
				'input_new_class_id'  => 'require|number',
				'input_old_class_times'  => 'require|number',
				'input_new_class_times'  => 'require|number',
			];
			$msg = [
				'input_old_class_id.require' => '请选择原班级',
				'input_old_class_id.number' => '原班级数据不正确！',
				'input_student_id.require' => '请选择需调课学生',
				'input_student_id.number' => '学生数据不正确！',
				'input_new_class_id.require' => '请选择调入班级',
				'input_new_class_id.number' => '调入班级数据不正确！',
				'input_old_class_times.require' => '请输入原班级调课课次',
				'input_old_class_times.number' => '请正确输入原课次，如第二次课：“2”',
				'input_new_class_times.require' => '请输入调入班级课次',
				'input_new_class_times.number' => '请正确输入调入班级课次，如第二次课：“2”',
			];

			$validate = new Validate($rule,$msg);
			$result   = $validate->check($param);
			if(!$result){
				$this->error($validate->getError());
			}
			// 开始调课操作
			// 查询并验证查课表
			$old_class = db('class_timetable')->where(['class_id'=>$param['input_old_class_id'],'times'=>$param['input_old_class_times']])->find();
			if(!$old_class){
				$old_problem = db('class_timetable')->where(['class_id'=>$param['input_old_class_id']])->find();
				if(!$old_problem){
					$this->error('当前班级未排课！请排课后操作！');
				}
				else{
					if($old_problem['class_number']<$param['input_old_class_times']){
						$this->error('原班级课次大于班级最大课次！');
					}
					else{
						$this->error('当前课次未排课！请排课后操作！');
					}
				}
			}
			$new_class = db('class_timetable')->where(['class_id'=>$param['input_new_class_id'],'times'=>$param['input_new_class_times']])->find();
			if(!$new_class){
				$new_problem = db('class_timetable')->where(['class_id'=>$param['input_new_class_id']])->find();
				if(!$new_problem){
					$this->error('当前班级未排课！请排课后操作！');
				}
				else{
					if($new_problem['class_number']<$param['input_new_class_times']){
						$this->error('原班级课次大于班级最大课次！');
					}
					else{
						$this->error('当前课次未排课！请排课后操作！');
					}
				}
			}
			// 写入调课信息
			$data['student_id'] = $param['input_student_id'];
			$data['timetable_id'] = $old_class['id'];
			$data['target'] = $new_class['id'];
			$data['code'] = 2;
			$data['status'] = 1;
			$data['edit_id'] = cmf_get_current_admin_id();
			$data['last_edit_time'] = time();
			// 是否已有其他考勤记录
			$is_attendance = db('student_attendance')->where(['student_id'=>$data['student_id'],'timetable_id'=>$data['timetable_id']])->find();
			if($is_attendance&&$is_attendance['code']!=0){
				$this->error('已有考勤记录，不可调课！');
			}
			else{
				$res = db('student_attendance')->insert($data);
				if($res){
					$this->success('新增调课成功！',url('portal/WxAdmin/class_attendance_turn'));
				}
				else{
					$this->error('新增调课失败！');
				}
			}
		}
	}
}